//
//  HDGradeViewController.swift
//  Excited
//
//  Created by X140Yu on 6/13/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//

import UIKit
import PKHUD
import MJRefresh

class HDGradeViewController: UIViewController {
    
    var scoreArray = Array<HDScore>()
    let noNetWorkView = HDNoNetworkView()
    
    var tableView = UITableView()
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidLogin), name: HDUserDidLoginNotificationKey, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidLogout), name: HDUserDidLogoutNotificationKey, object: nil)
        
        view.addSubview(tableView)
        tableView.snp_makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        tableView.registerNib(UINib(nibName: "HDGradeTableViewCell", bundle: nil), forCellReuseIdentifier: "GradeCell")        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 63

        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            HDAPIService.sharedInstance.getScores({ [unowned self] (scores, error) in
                dispatch_async(dispatch_get_main_queue(), {
                    if let score = scores {
                        self.scoreArray = score
                        self.tableView.reloadData()
                    } else {
                        // TODO: error
                    }
                    self.tableView.mj_header.endRefreshing()
                })
            })
        })
    }
}

extension HDGradeViewController {
    func userDidLogin() {
        noNetWorkView.removeFromSuperview()
        
        // add tableview and make constraints
        view.addSubview(tableView)
        tableView.snp_makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        
        
        //        scoreArray = HDCache.getScoreArray()
        if scoreArray.count == 0 {
            //            fetchScore({ [unowned self] (scroeArray) in
            //                self.scoreArray = scroeArray
            //                self.tableView.reloadData()
            //            }) { (message) in
            //                HUD.flash(.LabeledError(title: message, subtitle: nil), delay: 1.0)
            //            }
        }
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            
            //            fetchScore({ [unowned self] (scroeArray) in
            //                self.scoreArray = scroeArray
            //                self.tableView.reloadData()
            //                self.tableView.mj_header.endRefreshing()
            //            }) { (message) in
            //                self.tableView.mj_header.endRefreshing()
            //                HUD.flash(.LabeledError(title: message, subtitle: nil), delay: 1.0)
            //            }
        })
        
        // view did load staff
    }
    
    func userDidLogout() {
        tableView.removeFromSuperview()
        
        scoreArray.removeAll()
        
        view.addSubview(noNetWorkView)
        noNetWorkView.snp_makeConstraints { (make) in
            make.center.equalTo(0)
            make.width.equalTo(200)
            make.height.equalTo(200)
        }
        
        tableView.mj_header = nil
    }
}

extension HDGradeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return scoreArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("GradeCell", forIndexPath: indexPath) as! HDGradeTableViewCell
        cell.selectionStyle = .None
        let score = scoreArray[indexPath.row]
        cell.nameLabel.text = score.name
        cell.descriptionLabel.text = score.type! + "    " + score.credit! + "分"
        cell.scoreLabel.text = score.score
        return cell
    }
}
